var olMap;
var linkageState = false;
var moveState = false;

function InitOlMap() {
    var projection = ol.proj.get("EPSG:3857");
    var resolutions = [];
    for (var i = 0; i < 19; i++) {
        resolutions[i] = Math.pow(2, 18 - i);
    }
    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions
    });
    var baidu_source = new ol.source.TileImage({
        projection: projection,
        tileGrid: tilegrid,
        tileUrlFunction: function(tileCoord, pixelRatio, proj) {
            if (!tileCoord) {
                return "";
            }
            var z = tileCoord[0];
            var x = tileCoord[1];
            var y = tileCoord[2];
            if (x < 0) {
                x = "M" + (-x);
            }
            if (y < 0) {
                y = "M" + (-y);
            }
            return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1";
        }
    });
    //百度地图
    var baidu_layer = new ol.layer.Tile({
        source: baidu_source
    });
    // var url = 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer';
    // var raster = new ol.layer.Tile({
    //     source: new ol.source.OSM({
    //         attributions: ""
    //     })
    // });
    olMap = new ol.Map({
        // layers: [
        //     new ol.layer.Tile({
        //         source: new ol.source.XYZ({
        //             url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=e7575892441098ae6813a8944ba5b2ba',
        //         }),
        //         isGroup: true,
        //         name: '天地图路网'
        //     }),
        //     new ol.layer.Tile({
        //         source: new ol.source.XYZ({
        //             url: 'https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=e7575892441098ae6813a8944ba5b2ba'
        //         }),
        //         isGroup: true,
        //         name: '天地图文字标注'
        //     })
        // ],
        layers: [baidu_layer],
        target: 'olMap',
        view: new ol.View({
            //center: ol.proj.fromLonLat([103.73, 36.03]),
            zoom: 8,
            minZoom: 2,
            maxZoom: 21
        }),
        controls: ol.control.defaults({
            attributionOptions: {
                collapsible: false
            }
        })
    });
    olMap.on('pointerdrag', function(e) {
        if (linkageState) {
            if (moveState == true) { return moveState = false; }
            moveState = true;
            var mapExtent = olMap.getView().calculateExtent(olMap.getSize());
            let first = ol.proj.transform([mapExtent[0], mapExtent[1]], 'EPSG:3857', 'EPSG:4326');
            let second = ol.proj.transform([mapExtent[2], mapExtent[3]], 'EPSG:3857', 'EPSG:4326');
            viewer.camera.setView({
                destination: Cesium.Rectangle.fromDegrees(first[0], first[1], second[0], second[1])
            });
        }
    });

    olMap.getView().on('change:resolution', function(e) {
        if (linkageState) {
            if (moveState == true) { return moveState = false; }
            moveState = true;
            var mapExtent = olMap.getView().calculateExtent(olMap.getSize());
            let first = ol.proj.transform([mapExtent[0], mapExtent[1]], 'EPSG:3857', 'EPSG:4326');
            let second = ol.proj.transform([mapExtent[2], mapExtent[3]], 'EPSG:3857', 'EPSG:4326');
            viewer.camera.setView({
                destination: Cesium.Rectangle.fromDegrees(first[0], first[1], second[0], second[1])
            });
        }
    });

    linkage3DTo2D();

    // viewer.scene.postRender.addEventListener(function () {
    //     if (linkageState) {
    //         linkage3DTo2D();
    //     }
    // });

    viewer.scene.camera.moveEnd.addEventListener(function() {
        if (linkageState) {
            if (moveState == true) { return moveState = false; }
            moveState = true;
            linkage3DTo2D();
        }
    });

    //监听指定开关
    form.on('switch(switchLinkage)', function(data) {
        linkageState = this.checked;
        if (linkageState) {
            moveState = true;
            linkage3DTo2D()
        } else {
            moveState = false;
        }
    });
}

function linkage3DTo2D() {
    var rectangle = viewer.camera.computeViewRectangle();
    var west = rectangle.west / Math.PI * 180;
    var north = rectangle.north / Math.PI * 180;
    var east = rectangle.east / Math.PI * 180;
    var south = rectangle.south / Math.PI * 180;
    let bigger_box = { 'lng_min': west, 'lng_max': east, 'lat_min': south, 'lat_max': north };
    var topLeft = [parseFloat(bigger_box['lng_min']), parseFloat(bigger_box['lat_max'])];
    var topRight = [parseFloat(bigger_box['lng_max']), parseFloat(bigger_box['lat_max'])];
    var bottomLeft = [parseFloat(bigger_box['lng_min']), parseFloat(bigger_box['lat_min'])];
    var bottomRight = [parseFloat(bigger_box['lng_max']), parseFloat(bigger_box['lat_min'])];
    var p1 = ol.proj.transform(topLeft, 'EPSG:4326', 'EPSG:3857');
    var p2 = ol.proj.transform(topRight, 'EPSG:4326', 'EPSG:3857');
    var p3 = ol.proj.transform(bottomLeft, 'EPSG:4326', 'EPSG:3857');
    var p4 = ol.proj.transform(bottomRight, 'EPSG:4326', 'EPSG:3857');
    var coor_bigger_box = [p1, p2, p4, p3];
    // console.log(coor_bigger_box);
    var shape_tmp = new ol.Feature({
        geometry: new ol.geom.Polygon([coor_bigger_box])
    });
    let tmpLayer = new ol.layer.Vector({
        source: new ol.source.Vector(),
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'rgba(0,0,0,0)',
                width: 2,
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0,0,0,0)',
            })
        }),
    });
    tmpLayer.getSource().addFeature(shape_tmp);
    var feature = tmpLayer.getSource().getFeatures()[0];
    var polygon = (feature.getGeometry());
    var size = (olMap.getSize());
    olMap.getView().fit(polygon, size, { padding: [0, 0, 0, 0], constrainResolution: false });
    let heading = Cesium.Math.toDegrees(viewer.camera.heading).toFixed(2);
    olMap.getView().setRotation((360 - heading) * 0.01745);
}